const app = getApp();
var util =  require('../../../utils/util.js');
//防止重复购买
var isBuy = false;
Page({

    /**
     * 页面的初始数据
     */
    data: {
      yunfei:0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        util.setNavBarTitle('确认订单');
        console.log(options);
        let shopId = options.id;
        this.setData({
            shopId:shopId
        })
        this.getShoppingcart(shopId);
        this.getShopContentDetails(shopId);
    },
    //获取商家信息
    getShopContentDetails(shopId){
        let that = this;
        util.getAjax(`${app.globalData.apiUrl}/get_community_service_shop_content`,function(res){
            console.log(res);
            that.setData({
                shopInfo:res.data
            })
        },{id:shopId})
    },

    //shoppingcartList
    getShoppingcart(shopId){
        let that = this;
        util.getAjax(`${app.globalData.apiUrl}/get_user_community_service_shop_product_buycar`,function(res){
            console.log(res.data);
            that.setData({
                shoppingcartList:res.data,
            })
            that.getTotalMoney();
        },{shop_id:shopId,user_id: app.globalData.userId})
    },
    getTotalMoney(){
        let that = this;
        let shoppingcartList = that.data.shoppingcartList;
        let totalMoney = 0;
        for(let i in shoppingcartList){
            // for(let i=0;i<shoppingcartList.length;i++){
            totalMoney += shoppingcartList[i].num * shoppingcartList[i].price
        }

        that.setData({
            totalMoney:(parseFloat(totalMoney)+parseFloat(that.data.yunfei)).toFixed(2)
        })

    },
    //支付
    buy(){
        var _this = this;
        console.log(isBuy);
        if(isBuy)return;
        isBuy = true;
        if(_this.data.isAddress){
            var addressList = _this.data.addressList;
            if(addressList){
                var order_content = {
                    user_id:addressList.user_id,
                    community_service_shop_id:_this.data.shopId,
                    sheng:addressList.sheng,
                    shi:addressList.shi,
                    qu:addressList.qu,
                    address:addressList.address,
                    name:addressList.name,
                    phone:addressList.phone,
                    order_price:_this.data.totalMoney,
                    shop_id:_this.data.shopId
                };
                var shoppingcartList = _this.data.shoppingcartList
                var all_product = [];
                var all_id = [];
                for(var i in shoppingcartList){
                    all_id.push(shoppingcartList[i].id);
                    var product = {
                        product_id:shoppingcartList[i].product_id,
                        num:shoppingcartList[i].num,
                        one_price:shoppingcartList[i].price,
                        all_price:shoppingcartList[i].num * shoppingcartList[i].price
                    }
                    all_product.push(product);
                }

                console.log(all_id,all_product,order_content);
                order_content = JSON.stringify(order_content);
                all_product = JSON.stringify(all_product);
                util.postAjax(`${app.globalData.apiUrl}/community_service_shop_pay`,res =>{
                    console.log(res);
                    var orderNum = res.data.out_trade_no;
                    wx.requestPayment({
                        timeStamp:res.data.timeStamp,
                        nonceStr:res.data.nonceStr,
                        package:res.data.package,
                        signType:res.data.signType,
                        paySign:res.data.paySign,
                        success(res){
                            if(res.errMsg == 'requestPayment:ok'){
                                util.getAjax(`${app.globalData.apiUrl}/community_service_shop_pay_ok`,res=>{
                                    console.log(res);
                                    if(res.data == 1){
                                        isBuy = false;
                                        console.log('支付成功');
                                        wx.navigateTo({
                                            url:'/subPages/mine/orderDetails/orderDetails?orderNum='+orderNum+'&orderclass='+0
                                        })
                                    }
                                },{
                                    order_num:orderNum
                                })
                            }
                        },
                        fail(err){
                            // console.log(err);
                            isBuy = false;
                            wx.navigateTo({
                                url:'/subPages/mine/orderDetails/orderDetails?orderNum='+orderNum+'&orderclass='+0
                            })
                        }
                    })

                },{
                    order_content:order_content,
                    all_product: all_product,
                    all_id:all_id,
                    user_id:app.globalData.userId
                })

            }else{
                util.showToast('加载失败，请重试','none',1000)
                isBuy = false
            }
        }else{
            isBuy = false
            util.showModelAll('提示','请添加收货地址',function(){
                wx.navigateTo({
                    url: '/subPages/mine/newAddress/newAddress?isOne=' + 1,
                })
            })
        }


    },
    //获取地址数据
    getAddressData:function(){
        var that = this
        util.getAjax(app.globalData.apiUrl +'/get_user_address',function(res){
            console.log(res)
            if(res.data.length!=0){
                that.setData({
                    isAddress: true,
                    addressList: res.data[0],
                })
            }else{
                that.setData({
                    isAddress: false,
                    addressList: [],
                })
                util.showModelAll('提示','请添加收货地址',function(){
                    wx.navigateTo({
                        url: '/subPages/mine/newAddress/newAddress?isOne=' + 1,
                    })
                })
            }
        },{type:1,user_id: that.data.userId})
    },


    //地址管理
    addressBtn:function(){
        wx.navigateTo({
            url: '/subPages/mine/address/address',
        })
    },

    //新增地址管理
    newAddressBtn:function(){
        wx.navigateTo({
            url: '/subPages/mine/newAddress/newAddress?isOne=' + 1,
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var that = this
        if(app.globalData.userId){
            that.setData({
                userId: app.globalData.userId
            })
            that.getAddressData()
        }else{
            app.userIdCallback = userId => {
                if (userId != '') {
                    that.setData({
                        userId: userId
                    });
                    that.getAddressData()
                }
            }
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})
